//
//  ProjectTypeVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/13.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "ProjectTypeVC.h"

@interface ProjectTypeVC ()
{
    DVBarChartView *_chartView;
    NSMutableArray *_valueArr;
    NSMutableArray *_NameArr;
    NSMutableArray *_proportionArr;
    NSInteger max;
    UILabel *_title1;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation ProjectTypeVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(notice) name:@"123" object:nil];
    
    //获取通知中心单例对象
    NSNotificationCenter * center1 = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center1 addObserver:self selector:@selector(notice1) name:@"456" object:nil];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _valueArr = [[NSMutableArray alloc]init];
    _NameArr = [[NSMutableArray alloc]init];
    _proportionArr = [[NSMutableArray alloc]init];
    _dataSource = [[NSMutableArray alloc]init];

    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *dele = app.delegate;
    self.userID = dele.userId;
    [self load];
}
- (void)notice{
    _chartView.alpha = 1;
    _title1.alpha = 1;
    _tableview.alpha = 0;
}
- (void)notice1{
    _chartView.alpha = 0;
    _title1.alpha = 0;
    _tableview.alpha = 1;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"123" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"456" object:nil];
    
}

- (void)initTableView{
    
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 104, kSCREEN_WIDTH, kSCREEN_HEIGHT-104) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.backgroundColor = UIColorFromRGB(0xe6e6e6);
    //去掉多余的cell
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableview setTableFooterView:v];
    [self.view addSubview:_tableview];
    _tableview.alpha = 0 ;
}

- (void)initScroll{

    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 109, kSCREEN_WIDTH, 21)];
    title.text = @"各项目类型设备统计";
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = UIColorFromRGB(0x0093d5);
    [self.view addSubview:title];
    _chartView = [[DVBarChartView alloc] initWithFrame:CGRectMake(0, 130, kSCREEN_WIDTH, kSCREEN_HEIGHT-130)];
    [self.view addSubview:_chartView];
    
    
    _chartView.yAxisViewWidth = 52;
    _chartView.numberOfYAxisElements = 5;
    _chartView.xAxisTitleArray = _NameArr;
    
    _chartView.xValues = _valueArr;
    
    _chartView.delegate = self;
    _chartView.yAxisMaxValue = max;
    //    chartView.barUserInteractionEnabled = NO;
    [_chartView draw];

}

- (void)load{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";

    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_YunYcount parameters:@{@"type":@3,userid:[NSString stringWithFormat:@"%ld",self.userID]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YYProDataModel *model = [[YYProDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (PtypeModel *pModel in model.Ptype) {
            [_valueArr addObject:[NSString stringWithFormat:@"%ld",pModel.value]];
            [_proportionArr addObject:[NSString stringWithFormat:@"%.f",pModel.percent]];
            [_NameArr addObject:pModel.ptype];
            [_dataSource addObject:pModel];
            
        }
        if (_dataSource.count == 0) {
            
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 110, kSCREEN_WIDTH, kSCREEN_HEIGHT-110) title:@"不好...暂时没有数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
            
        }else{

        max = [[_valueArr valueForKeyPath:@"@max.intValue"]integerValue];
        [self initScroll];
        [self initTableView];
            [self.tableview reloadData];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
}
- (void)NothingRefresh:(UIButton *)sender{
    [_nothing removeFromSuperview];
    [self load];
}
/*失败刷新按键代理方法*/
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self load];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self load];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self load];
}
#pragma mark-->tableviewdelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return _dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 70.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *heard = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 70)];
    heard.backgroundColor = [UIColor whiteColor];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, kSCREEN_WIDTH, 21)];
    title.text = @"各项目类型设备统计";
    title.textColor = UIColorFromRGB(0x0093d5);
    title.textAlignment = NSTextAlignmentCenter;
    [heard addSubview:title];
    
    UILabel *CompanyT = [[UILabel alloc]initWithFrame:CGRectMake(10, 45, kSCREEN_WIDTH-185, 21)];
    CompanyT.text = @"项目类型";
    CompanyT.textColor = UIColorFromRGB(0x0093d5);
    [heard addSubview:CompanyT];
    UILabel *GzNumb = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(CompanyT.frame), 45, 80, 21)];
    GzNumb.text = @"设备数";
    GzNumb.textColor = UIColorFromRGB(0x0093d5);
    GzNumb.textAlignment = NSTextAlignmentCenter;
    [heard addSubview:GzNumb];
    UILabel *proportion = [[UILabel alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH-90, 45, 80, 21)];
    proportion.text = @"比例(%)";
    proportion.textColor = UIColorFromRGB(0x0093d5);
    proportion.textAlignment = NSTextAlignmentCenter;
    [heard addSubview:proportion];
    return heard;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 44.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    

        
    GZcountProjectCell *cell = [[GZcountProjectCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    cell.backgroundColor = UIColorFromRGB(0xf0f0f0);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PtypeModel *model = _dataSource[indexPath.row];
    [cell fillCellWithModel:model];
    
    return cell;
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}



@end
